package bll

import (
	"context"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"
)

type firstFaultType struct {
	iFirstFaultType store.IFirstFaultType
}

var FirstFaultType = &firstFaultType{
	iFirstFaultType: postgres.FirstFaultType,
}

func (a *firstFaultType) init() func() {
	return func() {}
}

func (a *firstFaultType) onEvent(*event.Data) {}

// Create 创建
func (a *firstFaultType) Create(ctx context.Context, in *model.FirstFaultTypeCreateRequest) error {
	var (
		err error
	)

	// 构建创建现场数据
	c := buildFirstFaultType(in)
	_, err = a.iFirstFaultType.Create(ctx, c)
	return err
}

// Update 更新
func (a *firstFaultType) Update(ctx context.Context, in *model.FirstFaultTypeUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt

	if in.Name != nil {
		dict["name"] = in.Name
	}

	if in.Desc != nil {
		dict["desc"] = in.Desc
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here

	// 更新前先删除
	CacheFaultType.DeleteFirstFaultType(in.Id)
	// 更新
	if err := a.iFirstFaultType.Update(ctx, in.Id, dict); err != nil {
		return err
	}
	// 更新后删除
	CacheFaultType.DeleteFirstFaultType(in.Id)
	return nil
}

// Delete 删除
func (a *firstFaultType) Delete(ctx context.Context, in *model.FirstFaultTypeDeleteRequest) error {
	return a.iFirstFaultType.Delete(ctx, in.Id)
}

// List 列表查询
func (a *firstFaultType) List(ctx context.Context, in *model.FirstFaultTypeListRequest) (*model.FirstFaultTypeListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.FirstFaultType
		out   = &model.FirstFaultTypeListResponse{}
	)

	if total, list, err = a.iFirstFaultType.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.FirstFaultTypesEntityToDto(list)

	return out, nil
}

// Find 列表查询
func (a *firstFaultType) Find(ctx context.Context, in *model.FirstFaultTypeInfoRequest) (*model.FirstFaultTypeInfo, error) {
	var (
		err  error
		data *entity.FirstFaultType
		out  = &model.FirstFaultTypeInfo{}
	)

	if data, err = a.iFirstFaultType.Find(ctx, in); err != nil {
		return nil, err
	}

	out = model.FirstFaultTypeEntityToDto(data)
	return out, nil
}

// buildFirstFaultType 构建创建数据现场
func buildFirstFaultType(in *model.FirstFaultTypeCreateRequest) *entity.FirstFaultType {
	// todo: check the entity is required
	return &entity.FirstFaultType{

		Name: in.Name,

		Desc: in.Desc,

		HasChild: in.HasChild,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
